import 'dart:io';

import 'package:agora_rtc_engine/agora_rtc_engine.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:videotop/base_model.dart';
import 'package:videotop/myinfo.dart';
import 'package:videotop/sql/databasehelper.dart';
import 'package:videotop/sql/msg_table.dart';
import 'package:videotop/sql/user_table.dart';
import 'package:videotop/util.dart';
import 'package:videotop/view/signin.dart';
import 'package:videotop/widget/videoPage.dart';

import '../evenbus.dart';

/// created by hx
///    2021/1/23:18:07

class HomeModel extends BaseModel{

  bool reg;
  BuildContext context;
  Util util;
  MyInfo myInfo;
  HomeModel(this.context, this.reg, this.util, this.myInfo);

  BasicMessageChannel messageChannel =
  const BasicMessageChannel('message', StringCodec());

  getInit() async{
    getSignin();
    util.getNativeLogin();

    messageChannel.setMessageHandler((message) => Future<String>((){
      print(message);
      if (Platform.isIOS) {
        message = message.substring(2);
      }
      List<String> list = message.split('__');
      if (list[3] == '文字') {
        //文字消息
        if (list[0].startsWith('挂断视频')) {
          bus.emit('offvideo', 1);
          doSendMsg(list[0], int.parse(list[1]), list[2], 3);
          return null;
        }
        if (list[0].startsWith('正在视频')) {
          bus.emit('offvideo', 0);
          doSendMsg(
              'The other party is talking', int.parse(list[1]), list[2], 0);
          return null;
        }
        if (list[0].startsWith('打开视频')) {
          DateTime nowtime = DateTime.now();
          DateTime msgtime =
          DateTime.fromMillisecondsSinceEpoch(int.parse(list[2]));
          if (msgtime.add(Duration(seconds: 30)).isAfter(nowtime)) {
            util.requestVoice(context).then((value) {
              if (value) {
                util.requestCamera(context).then((value) {
                  if (value) {
                    Navigator.of(context)
                        .push(MaterialPageRoute(builder: (context) {
                      return VideoPage(
                        false,
                        uid: int.parse(list[1]),
                        role: ClientRole.Broadcaster,
                        channelName: list[0].substring(4),
                      );
                    }));
                  } else {
                    util.showToast('Camera permission required');
                  }
                });
              } else {
                util.showToast('Microphone permission required');
              }
            });
          } else {
            doSendMsg('Missed video message', int.parse(list[1]),
                list[2], 0);
          }
          return null;
        }
        doSendMsg(list[0], int.parse(list[1]), list[2], 0);
      } else if (list[3] == '图片') {
        //图片消息
        doSendMsg(list[0], int.parse(list[1]), list[2], 1);
      }
      //可以又给android传回去
      return "回复消息";
    }));
  }

  getBackVideo(String uid) async {
    int id = int.parse(uid);
    util.getNativeYuid(id).then((value) {
      Future.delayed(Duration(seconds: 2), () {
        util.sendTextMessage('正在视频');
      });
    });
  }

  getSignin() {
    Future.delayed(Duration(seconds: 2), () {
      signin();
    });
  }

  signin() async{
    int ischeckin =  util.spfs.getInt('check_in${myInfo.uid}')??-1;
    util.spfs.setBool('check_in${myInfo.uid}',true);
    int day = util.spfs.getInt('qdday${myInfo.uid}')??0;
    var now = DateTime.fromMillisecondsSinceEpoch(util.urlTime);
    var count = now.difference(DateTime(now.year)).inDays;
    util.spfs.setInt('check_in${myInfo.uid}', count);
    if(count == ischeckin){
      return;
    }
    int cha = count - day;
    if(cha != 0){
      showDialog(
        // barrierDismissible: false,
          context: context,
          builder: (ctx) {
            return Signin(day);
          });
    }
  }

  void doSendMsg(String content, int uid, var times, int type) async {
    var db = new DatabaseHelper();

    //保存用户
    UserTable user1 = await db.getItem(uid);
    var nowtime = DateTime.now();
    if (user1 == null) {
      var map = await util.getBasicInfo(uid);
      UserTable user = new UserTable();
      user.uid = uid;
      user.times = times;
      user.icon = map['icon'];
      user.uptime = DateTime.now().millisecondsSinceEpoch.toString();
      user.nickname = map['nickname'];
      user.country = map['country'];
      user.vip = map['vip'];
      user.code = map['code'];
      user.birth = map['birth'];
      user.price = map['price'];
      db.saveItemUser(user);
    } else if (DateTime.fromMillisecondsSinceEpoch(int.parse(user1.uptime))
        .add(Duration(hours: 1))
        .isBefore(nowtime)) {
      var map = await util.getBasicInfo(uid);
      UserTable user = new UserTable();
      user.uid = uid;
      user.times = times;
      user.icon = map['icon'];
      user.uptime = DateTime.now().millisecondsSinceEpoch.toString();
      user.nickname = map['nickname'];
      user.country = map['country'];
      user.vip = map['vip'];
      user.code = map['code'];
      user.birth = map['birth'];
      user.price = map['price'];
      db.updateUser(user);
    }

    Msg msg = new Msg();
    msg.uid = uid;
    msg.state = 1;
    msg.times = times;
    msg.img = '';
    msg.video = '';
    msg.content = '';
    if (type == 1) {
      msg.img = content;
    } else if (type == 2) {
    } else if (type == 3) {
      msg.video = content.substring(4);
    } else if (type == 4) {
    } else {
      msg.content = content;
    }
    msg.type = 1;
    db.saveItemMsg(msg);
    //通知聊天UI
    bus.emit('chat', msg);
    util.setMsgCount(util.msgCount++);
    bus.emit('refresh');
  }


}